package com.itheima.dao;

import com.itheima.domain.Fruit;
import com.itheima.domain.User;



import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

public class ManagerDao {
    private static List<User> list = new ArrayList<>();

    private TreeSet<Fruit> fruitSet = new TreeSet<>();

    //读取文档中所有水果的信息，并各自封装进Fruit,再添加进list集合并返回
    public TreeSet<Fruit> getFruitSet() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("src\\com\\itheima\\info\\FruitInfo.txt"));

        fruitSet.clear();

        String s;
        while ((s = br.readLine()) != null) {
            String[] info = s.split(" ");
            Fruit fruit = new Fruit();

            fruit.setId(info[0]);
            fruit.setName(info[1]);
            fruit.setPrice(Double.parseDouble(info[2]));
            fruit.setAmount(Integer.parseInt(info[3]));
            fruitSet.add(fruit);
        }

        return fruitSet;
    }

    //判断水果id是否已经存在方法，已存在则返回true，否则返回false
    public boolean isIdExists(String id) throws IOException {
        fruitSet = getFruitSet();

        if (fruitSet.size() != 0) {
            for (Fruit fruit : fruitSet) {
                String fruitId = fruit.getId();
                if (id.equals(fruitId)) {
                    return true;
                }
            }
            //若for循环执行结束，该方法还未结束，代表水果id没有重复
            return false;
        } else {
            return false;
        }
    }

    //判断水果名称是否已经存在方法，已存在则返回true，否则返回false
    public boolean isNameExists(String newName) throws IOException {
        fruitSet = getFruitSet();

        if (fruitSet.size() != 0) {
            for (Fruit fruit : fruitSet) {
                String fruitName = fruit.getName();
                if (newName.equals(fruitName)) {
                    return true;
                }
            }
            //若for循环执行结束，该方法还未结束，代表水果名称没有重复
            return false;
        } else {
            return false;
        }

    }

    //上架水果方法
    public void addFruit(Fruit fruit) throws IOException {
        fruitSet = getFruitSet();

        fruitSet.add(fruit);

        writeFruitMethod(fruitSet);
    }

    //删除水果方法
    public void deleteFruit(String dleId) throws IOException {
        fruitSet = getFruitSet();

        fruitSet.removeIf(f -> dleId.equals(f.getId()));

        writeFruitMethod(fruitSet);
    }

    //修改水果方法
    public void updateFruit(Fruit fruit) throws IOException {
        fruitSet.clear();

        fruitSet.add(fruit);

        BufferedReader br = new BufferedReader(new FileReader("src\\com\\itheima\\info\\FruitInfo.txt"));

        String s;
        while ((s = br.readLine()) != null) {
            String[] split = s.split(" ");
            Fruit f = new Fruit(split[0], split[1], Double.parseDouble(split[2]), Integer.parseInt(split[3]));
            fruitSet.add(f);
        }

        writeFruitMethod(fruitSet);
    }

    //将fruitSet写入文件方法
    public void writeFruitMethod(TreeSet<Fruit> set) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("src\\com\\itheima\\info\\FruitInfo.txt"));

        for (Fruit f : set) {
            bw.write(f.getId() + " " + f.getName() + " " + f.getPrice() + " " + f.getAmount());
            bw.newLine();
        }

        bw.flush();
        bw.close();
    }




    //注册新用户
    public boolean addUser(User user){

        if(user == null){
            return false;
        }

        list.add(user);

        writMethod(list);

        return true;
    }

    //将集合中数据写入本地文件
    private void writMethod(List<User> list){
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter("src/com/itheima/info/UserInfo.txt"));
            for (User u : list) {
                bw.write(u.getId() + "," + u.getName() + "," + u.getBalance() + "," + u.getPoints() + "," + u.getPassword());
                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //判断用户是否存在
    public boolean isExists(String id) {
        for (User u : list) {
            if(u.getId().equals(id)){
                return true;
            }
        }
        return false;
    }

    //根据id获取单个用户
    public User selectById(String id) {
        list.clear();
        readMethod();
        int index = getIndex(id);
        return list.get(index);
    }

    //修改用户
    public boolean updateUserName(String id, String name){
        int index = getIndex(id);

        User u = list.get(index);
        u.setName(name);

        list.set(index,u);
        writMethod(list);

        return true;
    }

    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getId().equals(id)){
                index = i;
            }
        }
        return index;
    }

    //充值
    public void charGing(String id, double money) {
        int index = getIndex(id);

        User u = list.get(index);
        u.setBalance(u.getBalance() + money);

        list.set(index,u);
        writMethod(list);
    }

    //查询所有用户
    public List<User> selectAll() {
        list.clear();

        readMethod();

        return list;
    }

    //读取本地文件并添加集合

    public void readMethod() {
        BufferedReader br = null;

        if(list == null){
            return;
        }
        try {

            br = new BufferedReader(new FileReader("src/com/itheima/info/UserInfo.txt"));

            String s;
            while((s = br.readLine()) != null){
                String[] str = s.split(",");

                User u = new User();
                u.setId(str[0]);
                u.setName(str[1]);
                u.setBalance(Double.parseDouble(str[2]));
                u.setPoints(Integer.parseInt(str[3]));
                u.setPassword(str[4]);

                list.add(u);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //注销用户
    public void deleteUser(String id) {
        int index = getIndex(id);
        list.remove(index);
        writMethod(list);
    }

    //积分兑换
    public void pointsExchange(String id, int i) {
        int index = getIndex(id);
        User u = list.get(index);

        if(u.getPoints() >= i){
            u.setPoints(i);
            list.set(index,u);
            writMethod(list);
            System.out.println("兑换成功");
        }else {
            System.out.println("兑换失败，积分不足");
        }
    }
}
